package com.gitee.smsdistribution.service;

import com.gitee.smsdistribution.common_response.exception.UnAuthorizedException;
import com.gitee.smsdistribution.model.User;
import com.gitee.smsdistribution.repository.UserRepository;
import com.gitee.smsdistribution.util.Constant;
import com.gitee.smsdistribution.util.CookiesUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

@AllArgsConstructor
@Service
public class UserService {

    private final UserRepository userRepository;


    public void login(User user, HttpServletResponse response) {
        User searchedUser = userRepository.findByName(user.getName());
        if (Objects.isNull(searchedUser)) {
            throw new UnAuthorizedException("用户不存在", Map.of(Constant.NAME, user.getName()));
        }
        if (!searchedUser.getPassword().equals(user.getPassword())) {
            throw new UnAuthorizedException("密码错误", Map.of(Constant.NAME, user.getName()));
        }

        CookiesUtil.setCookie(response, Constant.ID, searchedUser.getId().toString(), null);
        CookiesUtil.setCookie(response, Constant.NAME, searchedUser.getName(), null);
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        CookiesUtil.deleteCookieByName(request, response, Constant.ID);
        CookiesUtil.deleteCookieByName(request, response, Constant.NAME);
    }
}
